package com.iwhalecloud.bss.kite.cucc.service.attr.handler;

import com.iwhalecloud.bss.kite.common.constant.SymbolConsts;
import com.iwhalecloud.bss.kite.common.util.KiteStringUtils;
import com.iwhalecloud.bss.kite.cucc.client.api.attr.IUnicomRegionService;
import com.iwhalecloud.bss.kite.cucc.client.dto.attr.UnicomRegion;
import com.iwhalecloud.bss.kite.cucc.client.dto.cust.CuccContextCustDTO;
import com.iwhalecloud.bss.kite.cucc.service.cache.CuccContextCustCache;
import com.iwhalecloud.bss.kite.manager.inst.KiteAttr;
import com.iwhalecloud.bss.kite.manager.inst.KiteInst;
import com.iwhalecloud.bss.kite.service.attr.data.CustAttrData;
import com.iwhalecloud.bss.kite.service.attr.handler.AbstractAttrHandler;
import com.ztesoft.bss.common.util.ContextUtil;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @ClassName : UserRegionHandler
 * @Description : 用户归属
 * @Author : xie.zhengjun
 * @Date : 2020/9/19 14:22
 */
public class UserRegionHandler extends AbstractAttrHandler<KiteInst, CustAttrData> {
    @Resource
    private IUnicomRegionService unicomRegionService;
    
    @Override
    public void def(KiteAttr attr, KiteInst inst, CustAttrData data) {
        if (KiteStringUtils.isEmpty(attr.getValue())) {
            CuccContextCustDTO cuccContextCustDTO = CuccContextCustCache
                .get(ContextUtil.getSimpleLoginInfo().getStaffCode(), data.getCustId());
            if (Objects.nonNull(cuccContextCustDTO)) {
                List<String> regionCodes = new ArrayList<>();
                regionCodes.add(cuccContextCustDTO.getProvinceCode());
                regionCodes.add(cuccContextCustDTO.getLanId());
                regionCodes.add(cuccContextCustDTO.getRegionId());
                attr.setDefaultValue(KiteStringUtils.join(regionCodes, SymbolConsts.COMMA));
                attr.setValue(KiteStringUtils.join(regionCodes, SymbolConsts.COMMA));
            }
        }
        super.def(attr, inst, data);
    }
    @Override
    public void after(KiteAttr attr, KiteInst inst, CustAttrData data) {
        super.after(attr, inst, data);
        attr.setValueDesc(getValueDesc(attr, inst, attr.getValue(), data));
    }
    
    @Override
    public String getValueDesc(KiteAttr attr, KiteInst inst, String value, CustAttrData data) {
        if (KiteStringUtils.isEmpty(value)) {
            return "";
        }
        String[] regionCodes = KiteStringUtils.split(value, SymbolConsts.COMMA);
        List<String> regionNames = Arrays.stream(regionCodes).map(s -> {
            UnicomRegion region = unicomRegionService.getRegion(s);
            return Objects.nonNull(region) ? region.getRegionName() : "";
        }).collect(Collectors.toList());
        return KiteStringUtils.join(regionNames, SymbolConsts.HYPHEN);
    }
}
